package cn.dgut.jy.soro.controller;

import cn.dgut.jy.soro.service.OrderService;
import cn.dgut.jy.soro.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class OrderController {
    private OrderService orderService;
    private UserService userService;

    @Autowired
    public OrderController(OrderService orderService, UserService userService) {
        this.orderService = orderService;
        this.userService = userService;
    }

    @RequestMapping(value = "/myOrders")
    String myOrders(HttpSession session, Model model) {
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId == null) {
            model.addAttribute("message", "请先登录");
            return "/login";
        }

        model.addAttribute("ordersMap", orderService.getOrders(userId));
        return "/myOrders";
    }

    @RequestMapping(value = "/ordering", method = RequestMethod.POST)
    String ordering(HttpSession session, Model model, @RequestParam String address, @RequestParam String consignee, @RequestParam String mobile, @RequestParam String str) {
        System.out.println(address + ",");
        System.out.println(consignee + ",");
        System.out.println(mobile + ",");
        System.out.println(str);
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId == null) {
            model.addAttribute("message", "请先登录");
            return "/login";
        }
        orderService.createOrder(userId, address, consignee, mobile, str);
        return "/myOrders";
    }

    @RequestMapping(value = "/checkOrders")
    String checkOrders(HttpSession session, Model model) {
        Integer userId = (Integer) session.getAttribute("userId");
        if(userId == null) {
            model.addAttribute("message", "请先登录");
            return "/login";
        }
        model.addAttribute("ordersMap", orderService.getAllOrders());

        return "checkOrders";
    }
}
